#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from subprocess import call
import os
import errno

zt_source_raw = '/data/www/css-js-image.hunantv.com/zt/proj-raw/'
zt_source_publish = '/data/www/css-js-image.hunantv.com/zt/'
zt_front_hist = '/home/ansible/front_page/zt/version-hist/'
remote_ip = '10.1.172.58'
# romote_ip = '192.168.3.101'

# 创建目录 mkdir -p
def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

# 写入文件
def jsonFile(fileData, filePath):
    file = open(filePath,"w")
    file.write(fileData)
    file.close()

# 文件发布
def publish(project, version):

    ret = 0
    src = zt_source_publish + project + '/' + version
    # css
    if os.path.isdir(src + '/css/'):
        # 创建远程目录/同步
        cmd_mkdir = "ansible %s -m file -a \"path=/data/www/css.hunantv.com/zt/%s/ state=directory\"" % (remote_ip, project)
        cmd_rsync = "ansible %s -m synchronize -a \"src=%s%s/%s/css/ dest=/data/www/css.hunantv.com/zt/%s/ recursive=yes delete=yes\"" % (remote_ip, zt_source_publish, project, version, project)
        ret += call(cmd_mkdir, shell=True)
        ret += call(cmd_rsync, shell=True)

    # js
    if os.path.isdir(src + '/js/'):
        # 创建远程目录/同步
        cmd_mkdir = "ansible %s -m file -a \"path=/data/www/js.hunantv.com/zt/%s/ state=directory\"" % (remote_ip, project)
        cmd_rsync = "ansible %s -m synchronize -a \"src=%s%s/%s/js/ dest=/data/www/js.hunantv.com/zt/%s/ recursive=yes delete=yes\"" % (remote_ip, zt_source_publish, project, version, project)
        ret += call(cmd_mkdir, shell=True)
        ret += call(cmd_rsync, shell=True)

    # img
    if os.path.isdir(src + '/image/'):
        # 创建远程目录/同步
        cmd_mkdir = "ansible %s -m file -a \"path=/data/www/img.hunantv.com/zt/%s/ state=directory\"" % (remote_ip, project)
        cmd_rsync = "ansible %s -m synchronize -a \"src=%s%s/%s/image/ dest=/data/www/img.hunantv.com/zt/%s/ recursive=yes delete=yes\"" % (remote_ip, zt_source_publish, project, version, project)
        ret += call(cmd_mkdir, shell=True)
        ret += call(cmd_rsync, shell=True)

    # flush
    cmd = "curl 'http://wscp.lxdns.com:8080/wsCP/servlet/contReceiver?username=staic&passwd=78fff9dc51f3c6b5b17fb2329fef44c5&dir=css.hunantv.com;js.hunantv.com;img.hunantv.com'"
    ret += call(cmd, shell=True)

    return ret

# 创建相应目录
dirs = [zt_source_raw, zt_source_publish, zt_front_hist]
for dir in dirs:
    mkdir_p(dir)

# 直接读取version文件，获得project
zt_version_file = zt_source_raw + '/version.json'
if os.path.isfile(zt_version_file):
    with open(zt_version_file) as data_file:
        data = json.load(data_file)
else:
    print("file '" + zt_version_file + "' is not exist!")
    exit(2)

pub_project = data['project']

# pub_project 不能为空
if pub_project is None or pub_project is "":
    print('project name should not be None!')
    exit(3)

# 获取project的last version
version_hist_file = zt_front_hist + pub_project + '.json'
if os.path.isfile(version_hist_file):
    with open(version_hist_file) as json_data:
        version_hist_src = json.load(json_data)

    #- 更新项目发布的json信息
    swap_version = version_hist_src['last']
    version_hist_src['last'] = version_hist_src['release']
    version_hist_src['release'] = swap_version
    pub_version = version_hist_src['release']['tag']

    # 发布代码
    ret = publish(pub_project, pub_version)
    if ret == 0:
        version_hist = json.dumps(version_hist_src)
        jsonFile(version_hist, version_hist_file)

else:
    print("this project is *not exist* !!!")
    exit(2)
